import React, { memo, useEffect, useState } from 'react';
import { CircleLoading } from '@/components/loading';
import './file-viewer.scss';
interface Props {
  previewUrl: string;
  loading: boolean;
  setLoading: (loading: boolean) => void;
  fileName?: string;
}

const VIDEO_EXTENSIONS = ['mp4', 'webm', 'mov', 'avi', 'flv', 'mkv', 'wmv'];

const VideoPreviewer = ({ previewUrl, loading, setLoading, fileName = '' }: Props) => {
  const [isError, setIsError] = useState(false);
  const [isVideo, setIsVideo] = useState(true);

  // 检测文件是否为视频类型
  // useEffect(() => {
  //   setIsError(false);
  //   setLoading(true);


  //   const fileExt = fileName.split('.').pop()?.toLowerCase();
  //   const isVideoFile = fileExt && VIDEO_EXTENSIONS.includes(fileExt);
  //   setIsVideo(isVideoFile);

  //   if (!isVideoFile) {
  //     setIsError(true);
  //     setLoading(false);
  //   }
  // }, [fileName, previewUrl, setLoading]);

  const handleVideoLoad = () => {
    setLoading(false);
    setIsError(false);
  };

  const handleVideoError = () => {
    setIsError(true);
    setLoading(false);
  };

  return (
    <div className="relative h-full w-full bg-black">
      {previewUrl ? (
        <React.Fragment>
          {isVideo && !isError && (
            <video
              src={previewUrl}
              controls
              autoPlay={false}
              muted
              playsInline
              className="h-full w-full object-contain"
              onLoadedData={handleVideoLoad}
              onError={handleVideoError}
            />
          )}

          {(isError || !isVideo) && (
            <div className="absolute inset-0 flex items-center justify-center text-white">
              {isError ? '视频加载失败，请检查文件链接' : '不支持的文件类型（仅支持视频格式）'}
            </div>
          )}

          {loading && (
            <div className="absolute inset-0 flex items-center justify-center">
              <CircleLoading />
            </div>
          )}
        </React.Fragment>
      ) : (
        <div className="absolute inset-0 flex items-center justify-center text-white text-center">
          文件不可用或可能已被删除
        </div>
      )}
    </div>
  );
};

export default memo(VideoPreviewer);